package com.xyyl.patient.common.oss;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.vo.base.FileUploadRecord;

/**
 * @ClassName: AliyunCloudStorageService
 * @Description:阿里云存储
 * @author chen
 * @date 2017年8月17日
 *
 */
@Component
public class AliyunCloudStorageService {

	private static Logger logger = LogManager.getLogger(AliyunCloudStorageService.class);

	// 阿里云绑定的域名
	private static String aliyunDomain;

	@Value("#{aliyun['oss.domain']}")
	public void setAliyunDomain(String domain) {
		aliyunDomain = domain;
	}

	// 阿里云EndPoint
	private static String aliyunEndPoint;

	@Value("#{aliyun['oss.endPoint']}")
	public void setAliyunEndPoint(String endPoint) {
		aliyunEndPoint = endPoint;
	}

	// 阿里云AccessKeyId
	private static String aliyunAccessKeyId;

	@Value("#{aliyun['oss.accessKeyId']}")
	public void setAliAccessKeyId(String accessKeyId) {
		aliyunAccessKeyId = accessKeyId;
	}

	// 阿里云AccessKeySecret
	private static String aliyunAccessKeySecret;

	@Value("#{aliyun['oss.accessKeySecret']}")
	public void setAliyunAccessKeySecret(String accessKeySecret) {
		aliyunAccessKeySecret = accessKeySecret;
	}

	// 阿里云BucketName
	private static String aliyunBucketName;

	@Value("#{aliyun['oss.bucketName']}")
	public void setAliyunBucketName(String bucketName) {
		aliyunBucketName = bucketName;
	}

	/**
	 * 上传默认目录
	 */
	private static String aliyunDirectory;

	@Value("#{aliyun['oss.directory']}")
	public void setAliyunDirectory(String directory) {
		aliyunDirectory = directory;
	}

	public static OSSClient getOSSClient() {
		return new OSSClient(aliyunEndPoint, aliyunAccessKeyId, aliyunAccessKeySecret);
	}

	/**
	 * @Title: upload @Description: 简单文件上传 @param @param
	 * inputStream @param @param fileName @param @return 参数 @return String
	 * 返回类型 @throws
	 */
	public static FileUploadRecord upload(InputStream inputStream, String fileName) {
		return uploadFile(getPath(aliyunDirectory), inputStream, fileName);
	}

	/**
	 * @Title: upload @Description:返回完整文件路径 @param @param
	 * multipartFile @param @return 参数 @return String 返回类型 @throws
	 */
	public static FileUploadRecord upload(MultipartFile multipartFile) {

		InputStream inputStream = null;
		String fileName = null;

		try {
			inputStream = multipartFile.getInputStream();
			fileName = multipartFile.getOriginalFilename();
		} catch (IOException e) {
			logger.error("upload fail:{}", e);
		}

		return uploadFile(getPath(aliyunDirectory), inputStream, fileName);
	}

	public static FileUploadRecord upload(InputStream inputStream) {
		return uploadFile(getPath(aliyunDirectory), inputStream, null);
	}

	private static FileUploadRecord uploadFile(String path, InputStream inputStream, String fileName) {

		PutObjectResult putObjectResult = null;

		FileUploadRecord fileUploadRecord = null;

		OSSClient ossClient = null;

		try {
			ossClient = getOSSClient();

			String fullKey = path + "/" + fileName;

			putObjectResult = getOSSClient().putObject(aliyunBucketName, fullKey, inputStream);

			if (putObjectResult.getETag() != null) {

				fileUploadRecord = new FileUploadRecord();
				fileUploadRecord.setFilekey(fullKey);
				fileUploadRecord.setUploadtime(DateUtils.currentDatetime());
				fileUploadRecord.setFullurl(aliyunDomain + "/" + fullKey);
			}

			logger.debug("upload success");

		} catch (Exception e) {
			logger.error("upload fail:{}", e);
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (ossClient != null) {
				ossClient.shutdown();

			}

		}
		return fileUploadRecord;
	}

	/**
	 * @Title: deleteFile @Description: 根据key删除指定附件 @param @param fileKey
	 * 参数 @return void 返回类型 @throws
	 */
	public static void deleteFile(String fileKey) {
		try {
			getOSSClient().deleteObject(aliyunBucketName, fileKey);
			logger.debug("delete success");

		} catch (Exception e) {
			logger.error("delete fail:{}", e);
		}
	}

	private static String getPath(String directory) {
		// 生成uuid
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		// 文件路径
		String path = DateUtils.formatDatetime(new Date(), "yyyyMMdd") + "/" + uuid;

		if (StringUtils.isNotBlank(directory)) {
			path = directory + "/" + path;
		}

		return path;
	}

}
